#include "SLT.h"
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
SListNode* BuySListNode(SLTDataType x) {
	SListNode* new = (SListNode*)malloc(sizeof(SListNode));
	assert(new);
	new->data = x;
	new->next = NULL;
	return new;
}
void SListPrint(SListNode* plist) {
	if (plist == NULL) {
		printf("SList is NULL"); 
		return;
	}
	SListNode* cur = plist;
	while (cur) {
		printf("->%d",cur->data);
		cur = cur->next;
	}
	printf("->NULL\n");
}
void SListPushBack(SListNode** pplist, SLTDataType x) {
	if (*pplist == NULL) {
		SListNode* tail = BuySListNode(x);
		*pplist = tail;
	}
	else {
		SListNode* tail = *pplist;
		while ((tail)->next != NULL) {
	       tail = (tail)->next;
		} 
		SListNode* new = BuySListNode(x);
		tail->next= new;
	}
}
void SListPushFront(SListNode** pplist, SLTDataType x) {
	if (*pplist == NULL) {
		SListNode* head = BuySListNode(x);
		*pplist = head;
	}
	else {
		SListNode* first = *pplist;
		SListNode* head = BuySListNode(x);
		head->next = first;
		*pplist = head;
	}
}
void SListPopBack(SListNode** pplist) {
	/*if (*pplist == NULL)return ;
	SListNode* tail = *pplist;
	SListNode* pre = NULL;
	while (tail->next) {
		pre = tail;
		tail=tail->next;
	}
	if (pre == NULL) {
		free(tail);
		*pplist = NULL;
	}
	else {	
		free(pre->next);
	    pre->next = NULL;
	}*/
		assert(*pplist);
		SListNode* tail = *pplist;
		if (tail->next == NULL) {
			free(tail);
			*pplist = NULL;
			return;
		}
		while (tail->next->next != NULL) {
			tail = tail->next;
		}
		free(tail->next);
		tail->next = NULL;
	
}
void SListPopFront(SListNode** pplist) {
	if (*pplist == NULL)return;
	SListNode* fr = *pplist;
	*pplist=fr->next;
	free(fr);
};
SListNode* SListFind(SListNode* plist, SLTDataType x) {
	if (plist == NULL)return NULL;
	SListNode* fi = plist;
	while (fi!=NULL) {
		if (fi->data == x)return fi;
		fi = fi->next;
	}
	return NULL;
}
void SListInsertAfter(SListNode* pos, SLTDataType x) {
	if (pos == NULL)return;
	SListNode* ne = pos->next;
	SListNode*new=BuySListNode(x);
	new->next = ne;
	pos->next = new;
}
void SListErase(SListNode** plist, SListNode* pos){
	if (plist == NULL)return;
	if (*plist == NULL)return;
	SListNode* pre = *plist;
	while (pre->next != pos) {
		pre = pre->next;
	}
	pre->next = pos->next;
	free(pos);
	return;
}